package com.yj.forum.services.impl;

import com.yj.forum.common.AppResult;
import com.yj.forum.common.ResultCode;
import com.yj.forum.dao.MessageMapper;
import com.yj.forum.exception.ApplicationException;
import com.yj.forum.model.Message;
import com.yj.forum.model.User;
import com.yj.forum.services.IMessageService;
import com.yj.forum.services.IUserService;
import com.yj.forum.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class MessageServiceImpl implements IMessageService {
    @Resource
    private MessageMapper messageMapper;
    @Resource
    private IUserService userService;
    /**
     * 发送站内信息
     * @param message 站内信
     */
    @Override
    public void create(Message message) {
        //非空校验
        if(message == null
                || StringUtil.isEmpty(message.getContent())
                || message.getPostUserId() == null
                || message.getPostUserId() <= 0
                || message.getReceiveUserId() == null
                || message.getReceiveUserId() <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //校验接收者是否存在
        User user = userService.selectById(message.getReceiveUserId());
        if(user == null || user.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        // 设置默认值
        message.setState((byte) 0); // 表⽰未读状态
        message.setDeleteState((byte) 0);
        // 设置创建与更新时间
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);

        //调用dao
        int row = messageMapper.insertSelective(message);
        if(row != 1) {
            log.error(ResultCode.ERROR_SERVICES.toString()+ ", 受影响的⾏数不等于 1 为 " + row);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }


    }
    /**
     * 根据用户id查询该用户私信未读数
     * @param receiveUserId 用户id
     * @return 私信未读数
     */
    @Override
    public Integer selectUnreadCount(Long receiveUserId) {
        //非空校验
        if(receiveUserId == null || receiveUserId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //拿取用户
        User user = userService.selectById(receiveUserId);
        if (user == null || user.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS));
        }
        //调用dao
        Integer ret = messageMapper.selectUnreadCount(receiveUserId);

        return ret;
    }
    /**
     * 根据接收者Id查询所有站内信
     * @param receiveUserId 接收者Id
     * @return 站内信列表
     */
    @Override
    public List<Message> selectByReceiveUserId(Long receiveUserId) {
        //非空校验
        if(receiveUserId == null || receiveUserId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        List<Message> messages = messageMapper.selectByReceiveUserId(receiveUserId);

        return messages;
    }
    /**
     * 读取站内信
     *
     * @param id 站内信Id
     * @return 站内信
     */
    @Override
    public Message selectById(Long id) {
        //非空校验
        if(id ==null || id <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //调用dao
        Message message = messageMapper.selectByPrimaryKey(id);
        return message;
    }
    /**
     *  根据Id更新
     * @param id 站内信id
     * @param state 已读状态
     */
    @Override
    public void updateStateById(Long id, Byte state) {
        //非空校验
        if(id == null || id <= 0 ||  state < 0 || state > 2) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        //拿取站内信
        Message message = messageMapper.selectByPrimaryKey(id);
        //校验
        if(message == null || message.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_MESSAGE_IS_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_IS_NOT_EXISTS));
        }
        //构造数据 更新
        Message updateMessage = new Message();
        updateMessage.setId(id);
        updateMessage.setState(state);
        //调用dao
        int row = messageMapper.updateByPrimaryKeySelective(updateMessage);
        if(row != 1) {
            log.error(ResultCode.ERROR_SERVICES.toString()+ ", 受影响的⾏数不等于 1 为 " + row);
            throw new ApplicationException(AppResult.failed(ResultCode.ERROR_SERVICES));
        }

    }
    /**
     * 回复站内信
     * @param repliedId 被回复的站内信Id
     * @param message 回复内容
     */
    @Override
    public void reply(Long repliedId, Message message) {
        //非空校验
        if(repliedId == null || repliedId <= 0) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString());
            throw new  ApplicationException(AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE));
        }
        // 校验repliedId对应的站内信状态
        Message existsMessage = messageMapper.selectByPrimaryKey(repliedId);
        if (existsMessage == null || existsMessage.getDeleteState() == 1) {
            log.warn(ResultCode.FAILED_MESSAGE_IS_NOT_EXISTS.toString());
            throw new ApplicationException(AppResult.failed(ResultCode.FAILED_MESSAGE_IS_NOT_EXISTS));
        }
        // 更新状态为已回复
        updateStateById(repliedId, (byte) 2);
        // 回复的内容写⼊数据库
        create(message);


    }
}
